<template>
  <div class="home">
    <!-- 头部 -->
    <Header
      :addressList='addressList'
      :carIndex='carIndex'
      @goReceiving='goReceiving'/>

    <!-- 轮播图 -->
    <Banner
      :bannerList='bannerList'
      v-if="bannerList.length > 0"/>

    <!-- tab 切换 -->
    <div class="tabList">
      <van-tabs v-model="active" sticky :offset-top="42">
        <van-tab title="综合排序">
          <van-list
            v-model="loading"
            :finished="finished"
            finished-text="没有更多了"
            @load="onLoad"
          >
            <div
              v-for="(item, index) in searchList"
              :key="index">
                <ImgItem :item="item" />
            </div>
          </van-list>
        </van-tab>
        <van-tab title="距离最近">
          <div
            v-for="(item, index) in searchList.filter(item => item.type == 'jl')"
            :key="index">
              <ImgItem :item="item" />
          </div>
        </van-tab>
        <van-tab title="销量最高">
          <div
            v-for="(item, index) in searchList.filter(item => item.type == 'sl')"
            :key="index">
              <ImgItem :item="item" />
          </div>
        </van-tab>
        <van-tab title="筛选">
          <div
            v-for="(item, index) in searchList.filter(item => item.type == 'sx')"
            :key="index">
              <ImgItem :item="item" />
          </div>
        </van-tab>
      </van-tabs>
    </div>
  </div>
</template>

<script>
// vuex 辅助函数
import { mapState } from 'vuex';
import { getSearchList } from '@/api';

// 引入组件
import Header from '@/components/Header';
import Banner from '@/components/Banner';
import ImgItem from '@/components/ImgItem';

export default {
  name: 'Home',
  data() {
    return {
      active: 0,
      loading: false,
      finished: false,
    }
  },
  methods: {
    async onLoad() {
      // 开启家在状态
      this.loading = true;
      // 当前数组的长度小与总长度的时候
      if(this.searchList.length < this.count) {
        // 请求数据
        const searchList = await getSearchList({ pageSize: this.pageSize, pageNum: this.pageNum })
        // 存到 vuex 中
        this.$store.dispatch('getSearchList', searchList.data);
        

        // 关闭加载状态结束
        this.loading = false;

        // 数据全部加载完成
        if(this.searchList.length >= this.count) {
          this.finished = true;
        }
      }
    },
    // 跳转到地址列表页面
    goReceiving() {
      this.$router.push('/index/home/receiving');
    }
  },
  computed: {
    ...mapState(['addressList', 'carIndex', 'bannerList', 'searchList', 'pageSize', 'pageNum', 'count'])
  },
  components: {
    Header,
    Banner,
    ImgItem
  }
}
</script>

<style lang='scss'>
.tabList {
  padding-bottom: 56px;
  box-sizing: border-box;
}
</style>
